package com.ssoserver.controller;
import cn.hutool.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
 * @author zchcpywin10
 */
@Controller
@CrossOrigin
public class LoginController {
  final StringRedisTemplate redisTemplate;
  Map<String, String> map = new HashMap<>();
  Map<String, String> tokenMap = new HashMap<>();
  /**
   *
   * @param redisTemplate StringRedisTemplate
   */
  @Autowired
  public LoginController(StringRedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }
  @ResponseBody
  @GetMapping("/userInfo")
  public String userInfo(@RequestParam("token") String token) {
    return redisTemplate.opsForValue().get(token);
  }
  @ResponseBody
  @GetMapping("/test")
  public String test() {
    return "ok";
  }
  @GetMapping("/login.html")
  public String loginPage(@RequestParam("redirect_url") String url, Model model,
                          //
                          @CookieValue(value = "sso_token", required = false) String sso_token,
                          //
                          @RequestParam("url") String redurl, @RequestParam("jsessionId") String jsessionId) {
    map.put(redurl, jsessionId);
    if (!StringUtils.isEmpty(sso_token)) {
      //说明之前有人登录过，浏览器留下了痕迹
      return "redirect:" + url + "?token=" + sso_token;
    }
    model.addAttribute("url", url);
    return "login";
  }
  @PostMapping("/doLogin")
  public String doLogin(@RequestParam("username") String username,
                        //
                        @RequestParam("password") String password,
                        //
                        @RequestParam("url") String url, HttpServletResponse response, Model model) {
    if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
      //登录成功，跳回之前页面
      //把登录成功的用户存起来。
      String uuid = UUID.randomUUID().toString().replace("-", "");
      redisTemplate.opsForValue().set(uuid, username);
      Cookie ssoToken = new Cookie("sso_token", uuid);
      response.addCookie(ssoToken);
      tokenMap.put("token", uuid);
      return "redirect:" + url + "?token=" + uuid;
    }
    model.addAttribute("url", url);
    //登录失败，展示登录页
    return "login";
  }
  @GetMapping("/logout.html")
  public String logout(HttpServletResponse response, HttpSession session) {
    // 销毁全局session和cookie
    Cookie ssoToken = new Cookie("sso_token", null);
    ssoToken.setMaxAge(0);
    ssoToken.setPath("/");
    response.addCookie(ssoToken);
    session.invalidate();
    tokenMap.clear();
    try {
      if (map.size() > 0) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
          String url = entry.getKey();
          String sessionId = entry.getValue();
          // HttpRequest.get(url + "?jessionId=" + sessionId).setReadTimeout(10000).execute()
          HttpRequest.get(url + "?sessionId=" + sessionId).setReadTimeout(10000).execute();
        }
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    return "login";
  }
  @GetMapping("/checkToken")
  @ResponseBody
  public Boolean checkToken(@RequestParam("token") String token) {
    String cookie = tokenMap.get("token");
    return token.equals(cookie);
  }
}
